//
//  EJSGoodsDetailInfoViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/20.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSGoodsDetailInfoViewController.h"
#import "EJSGoodsEvaluateListViewController.h"

#ifdef ProjectXO//西欧
#import "XOShopDetailViewController.h"
#endif
#import "EJSUpgradeVipViewController.h"

#import "JSONKit.h"
#import "EJSGoodsVideoImageTableViewCell.h"
#import "EJSGoodsInfoTableViewCell.h"
#import "EJSGoodsDetailTableViewCell.h"
#import "EJSVipCell.h"
#import "EJSGoodsEvaluateTableViewCell.h"
#import "EJSEvaluateTableViewCell.h"
#import "XOSelectSpecTableViewCell.h"
#import "EJSSelectGoodsSpecView.h"

#import "EJSGoodsDetailInfoRequest.h"
#import "EJSGoodsAddCartRequest.h"
#import "EJSBuyNowRequest.h"
#import "EJSSettleViewController.h"
#import "XOShoppingCartListModel.h"
#import "XMMovableButton.h"
#import "EJSShoppingCartListRequest.h"
#import "EJSUpdateShopCartRequest.h"
#import "MMNumberKeyboard.h"

@interface EJSGoodsDetailInfoViewController ()<UITableViewDataSource,UITableViewDelegate,MMNumberKeyboardDelegate,UITextFieldDelegate>{
    NSInteger _segmentIndex;
}

@property (strong, nonatomic) EJSGoodsModel *goodsModel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet ImageTitleButton *selectSkuButton;
@property (weak, nonatomic) IBOutlet UIButton *subtractButton;
@property (weak, nonatomic) IBOutlet UITextField *addedNumberLabel;
@property (strong, nonatomic) XOShoppingCartListModel *shoppingCartListModel;
@property (weak, nonatomic) IBOutlet ImageTitleButton *shopCartButton;
@property (weak, nonatomic) IBOutlet UIButton *addToCartButton;

@property (strong, nonatomic) EJSGoodsSkuModel *selectSkuModel;
StrongProperty UISegmentedControl *customSegmentControl;
@end

@implementation EJSGoodsDetailInfoViewController
- (UISegmentedControl *)customSegmentControl {
    if (_customSegmentControl) {
        return _customSegmentControl;
    }
    NSArray *array = [NSArray arrayWithObjects:NSLocalizedString(@"包", nil),NSLocalizedString(@"箱", nil), nil];
    _customSegmentControl = [[UISegmentedControl alloc]initWithItems:array];
    _customSegmentControl.frame = CGRectMake(0, 0, self.view.frame.size.width * 0.5, 30);
    _customSegmentControl.selectedSegmentIndex = 0;
    [_customSegmentControl addTarget:self action:@selector(customSegment:) forControlEvents:UIControlEventValueChanged];
    return _customSegmentControl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getGoodsDetailInfo];
    FlyWeakSelf
    [[NSNotificationCenter defaultCenter] addObserverForName:EJSGoodsDetailWebViewDidLoadNotify object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        if(weakSelf.goodsModel.contentHeight.floatValue != [note.object floatValue]){
            weakSelf.goodsModel.contentHeight = note.object;
            [weakSelf.tableView reloadData];
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)createMovableButton{
    XMMovableButton *movableButton=[[XMMovableButton alloc] init];
    movableButton.frame = CGRectMake(ScreenWidth - 15 - 50, ScreenHeight / 2 + 50, 50, 50);

        //点击事件
    [movableButton addTarget:self action:@selector(movableButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    movableButton.margin = 15;
        //圆角
    movableButton.layer.cornerRadius = 25;
    movableButton.layer.masksToBounds = YES;
    movableButton.backgroundColor = AppMainColor;
        //按钮图片
    [movableButton setImage:[UIImage imageNamed:@"tabBarItem2_normal"] forState:UIControlStateNormal];

    [self.view addSubview:movableButton];
}

- (void)movableButtonClickAction {
    self.tabBarController.selectedIndex = 2;
}

    //MARK: 点击购物车
//- (void)rightBarButtonAction:(id)sender {
//    if([self userIsLogin]){
//        EJSGoodsDetailCartViewController * cartViewController = [EJSGoodsDetailCartViewController new];
//        cartViewController.modalPresentationStyle = UIModalPresentationPageSheet;
//        cartViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//        [self presentViewController:cartViewController animated:YES completion:nil];
//    }
//}


- (BOOL)prefersHomeIndicatorAutoHidden {
    return YES;
}

- (void)configOwnViews{
    self.title = NSLocalizedString(@"Commodity details", nil);
    self.navigationItem.titleView = self.customSegmentControl;
    _segmentIndex = 0;
    self.customSegmentControl.selectedSegmentIndex = 0;
    
    MMNumberKeyboard *keyboard = [[MMNumberKeyboard alloc] initWithFrame:CGRectZero];
    keyboard.allowsDecimalPoint = YES;
    keyboard.delegate = self;
    self.addedNumberLabel.inputView = keyboard;
    self.addedNumberLabel.delegate = self;
    
    
//    UIImage *shopCartImage = [UIImage imageNamed:@"tabBarItem2_select"];
//    [self.shopCartButton setImage:shopCartImage forState:UIControlStateNormal];
//    self.shopCartButton.imageSize = shopCartImage.size;
//    self.shopCartButton.padding = CGSizeMake(10, 0);
//    self.shopCartButton.style = EImageLeftTitleRightCenter;

    [self.addToCartButton setBackgroundColor:AppMainColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSGoodsVideoImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"EJSGoodsVideoImageTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSGoodsInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"EJSGoodsInfoTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSVipCell" bundle:nil] forCellReuseIdentifier:@"EJSVipCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSGoodsDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"EJSGoodsDetailTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSGoodsEvaluateTableViewCell" bundle:nil] forCellReuseIdentifier:@"EJSGoodsEvaluateTableViewCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"EJSEvaluateTableViewCell" bundle:nil] forCellReuseIdentifier:@"EJSEvaluateTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"XOSelectSpecTableViewCell" bundle:nil] forCellReuseIdentifier:@"XOSelectSpecTableViewCell"];
    
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.estimatedRowHeight = 50;
}



- (void)getGoodsDetailInfo{
    EJSGoodsDetailInfoRequest *req = [EJSGoodsDetailInfoRequest new];
    req.spuId = self.goodsId;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.goodsModel = response.data;
        [weakSelf.tableView reloadData];
        [weakSelf getCartList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

#pragma mark - Actions
- (void)selectGoodsSpecAction:(UIButton *)sender {
    FlyWeakSelf
    [EJSSelectGoodsSpecView showSelectGoodsSpecView:_goodsModel completion:^(EJSGoodsSkuModel *selectSkuModel) {
        weakSelf.selectSkuModel = selectSkuModel;
    }];
}
- (void)entryShopAction:(UIButton *)sender {

    
}
- (IBAction)addToShoppingCartAction:(UIButton *)sender {
    if([self userIsLogin]){
        if(_goodsModel.hasDefaultSku.integerValue == 1 && _goodsModel.skus.count > 0){
            self.selectSkuModel = _goodsModel.skus.firstObject;
            self.selectSkuModel.skuSelectCount = [self getAddedCount];
            [self addToCartReq:self.selectSkuModel];
            return;
        }
        FlyWeakSelf
        [EJSSelectGoodsSpecView showSelectGoodsSpecView:_goodsModel completion:^(EJSGoodsSkuModel *selectSkuModel) {
            [weakSelf addToCartReq:selectSkuModel];
        }];
    }
}

- (IBAction)subtractFromCartAction:(UIButton *)sender {
    for (XOShoppingCartModel *model in self.shoppingCartListModel.list) {
        for (EJSShoppingCartGoodsModel *cartGood in model.carts) {
            if ([cartGood.spuId isEqualToString:_goodsId]) {
                NSInteger selectNum = cartGood.num.intValue;
                if(selectNum - [self getAddedCount] > 0){
                    cartGood.num = @(selectNum - [self getAddedCount]).stringValue;
                }else if (selectNum - [self getAddedCount] <= 0){
                    cartGood.num = @"0";
                }
                [self updateShopCartRequest];
                return;
            }
        }
    }
}

- (void) deleteGoodsInCart {
    for (XOShoppingCartModel *model in self.shoppingCartListModel.list) {
        for (EJSShoppingCartGoodsModel *cartGood in model.carts) {
            if ([cartGood.spuId isEqualToString:_goodsId]) {
                cartGood.num = @"0";
                [self updateShopCartRequest];
                return;
            }
        }
    }
}

- (void) updateGoodsWithCustomNumber: (NSString *)number {
    for (XOShoppingCartModel *model in self.shoppingCartListModel.list) {
        for (EJSShoppingCartGoodsModel *cartGood in model.carts) {
            if ([cartGood.spuId isEqualToString:_goodsId]) {
                cartGood.num = number;
                [self updateShopCartRequest];
                return;
            }
        }
    }
}

-(void)customSegment: (UISegmentedControl *)segmentedControl{
    switch (segmentedControl.selectedSegmentIndex) {
        case 0:
            _segmentIndex = 0;
            break;
        default:
            _segmentIndex = 1;
            break;
    }
}

- (NSInteger) getAddedCount {
    if (_segmentIndex == 0) {
        return _goodsModel.packNum.integerValue;
    }
    return _goodsModel.boxNum.integerValue;
}

- (void)updateShopCartRequest{
    NSMutableArray *datas = [NSMutableArray array];
    for (EJSShoppingCartGoodsModel *goodsModel in self.shoppingCartListModel.wholeGoodsList) {
        if ((goodsModel.num.intValue == 0)) {
            continue;
        }
        EJSUpdateShopCartModel *model = [EJSUpdateShopCartModel new];
        model.cart_id = goodsModel.cartId;
        model.sku_id = goodsModel.spuId;
        model.num = goodsModel.num;
        [datas addObject:[model getJsonDictionary]];
    }

    EJSUpdateShopCartRequest *req = [EJSUpdateShopCartRequest new];
    req.data = [datas JSONString];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [self getCartList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)addToCartReq:(EJSGoodsSkuModel *)skuModel{
    EJSGoodsAddCartRequest *req = [EJSGoodsAddCartRequest new];
    req.skuId = skuModel.skuId;
    req.num = @(skuModel.skuSelectCount).stringValue;
    req.hideLoadingView = YES;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
//        [[HUDHelper sharedInstance] tipMessage:@"加入购物车成功"];
        if(weakSelf.selectSkuModel){
            weakSelf.selectSkuModel = nil;
        }
        [weakSelf getCartList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

#pragma mark - loadData
- (void)getCartList{
//    FlyWeakSelf
//    EJSShoppingCartListRequest *req = [EJSShoppingCartListRequest new];
//    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
//        weakSelf.shoppingCartListModel = response.data;
//    } failHandler:^(BaseResponse *response) {
//        [[HUDHelper sharedInstance] tipMessage: response.message];
//    }];
    
    if(![EJSUserTokenModel userTokenModel]){
        return;
    }
    FlyWeakSelf
    [[XOShopCartViewModel shared] updateCartList:^(XOShoppingCartListModel * _Nonnull response) {
        XOShoppingCartListModel *cartList = response;
        weakSelf.shoppingCartListModel = cartList;
    }];

}
- (void)setShoppingCartListModel:(XOShoppingCartListModel *)shoppingCartListModel {
    _shoppingCartListModel = shoppingCartListModel;
    [self updateUI];
}

- (void)updateUI{
    NSString * num = @"0";
    for (XOShoppingCartModel *model in self.shoppingCartListModel.list) {
        for (EJSShoppingCartGoodsModel *cartGood in model.carts) {
            if ([self.goodsId isEqualToString:cartGood.spuId]) {
                num = cartGood.num;
            }
        }
    }
    if (num.intValue == 0) {
        [UIView animateWithDuration:0.25 animations:^{
            self.subtractButton.alpha = 0.0;
        } completion:^(BOOL finished) {
            [self.subtractButton setHidden:YES];
        }];
    }else {
        [UIView animateWithDuration:0.25 animations:^{
            self.subtractButton.alpha = 1.0;
        } completion:^(BOOL finished) {
            [self.subtractButton setHidden:NO];
        }];
    }
    self.addedNumberLabel.text = num;
}
//- (void)buyNowRequest:(EJSGoodsSkuModel *)skuModel{
//    FlyWeakSelf
//    EJSBuyNowRequest *req = [EJSBuyNowRequest new];
//    req.skuId = skuModel.skuId;
//    req.num = @(skuModel.skuSelectCount).stringValue;
//    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
//        if(weakSelf.selectSkuModel){
//            weakSelf.selectSkuModel = nil;
//        }
//
//        EJSSettleViewController *settleVC = [[EJSSettleViewController alloc] initWithNibName:@"EJSSettleViewController" bundle:nil];
//
//        EJSShoppingCartGoodsModel *shoppingCarModel = [EJSShoppingCartGoodsModel new];
//        shoppingCarModel.spuName = _goodsModel.spuName;
//        shoppingCarModel.spuId = _goodsModel.spuId;
//        shoppingCarModel.specInfo = skuModel.specInfo;
//        shoppingCarModel.cover = _goodsModel.cover;
//        shoppingCarModel.price = skuModel.price;
//        shoppingCarModel.num = @(skuModel.skuSelectCount).stringValue;
//        shoppingCarModel.cartId = response.data;
//
//        settleVC.settleGoods = @[shoppingCarModel];
//        [weakSelf.navigationController pushViewController:settleVC animated:YES];
//
//    } failHandler:^(BaseResponse *response) {
//        [[HUDHelper sharedInstance] tipMessage:response.message];
//    }];
//}

#pragma mark - MMNumberKeyboardDelegate
- (BOOL)numberKeyboardShouldReturn:(MMNumberKeyboard *)numberKeyboard
{
    if (self.addedNumberLabel.text.length == 0) {
        [self deleteGoodsInCart];
        return YES;
    }else if (self.addedNumberLabel.text.intValue > 0){
        [self updateGoodsWithCustomNumber:self.addedNumberLabel.text];
        return YES;
    }
    [self deleteGoodsInCart];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.addedNumberLabel.text.length == 0) {
        [self deleteGoodsInCart];
    }else if (self.addedNumberLabel.text.intValue > 0){
        [self updateGoodsWithCustomNumber:self.addedNumberLabel.text];
    }else {
        [self deleteGoodsInCart];
    }
}


#pragma mark - UITableViewDataSource Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 2;
    }else if(section == 1){
        return _goodsModel.comments.list.count + 1;
    }else if(section == 2){
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        if(indexPath.row == 0){
            EJSGoodsVideoImageTableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"EJSGoodsVideoImageTableViewCell" forIndexPath:indexPath];
            [imageCell setGoodsModel:_goodsModel];
            return imageCell;
        }else if (indexPath.row == 1){
            EJSGoodsInfoTableViewCell *goodsInfoCell = [tableView dequeueReusableCellWithIdentifier:@"EJSGoodsInfoTableViewCell" forIndexPath:indexPath];
            [goodsInfoCell setGoodsName:_goodsModel.spuName price:_goodsModel.price originPrice:_goodsModel.originPrice];
            return goodsInfoCell;
        }
    }else if(indexPath.section == 1){
        if(indexPath.row == 0){
            EJSGoodsEvaluateTableViewCell *goodsEvaluateCell = [tableView dequeueReusableCellWithIdentifier:@"EJSGoodsEvaluateTableViewCell" forIndexPath:indexPath];
            if (_goodsModel.comments.totalPages != NULL) {
                goodsEvaluateCell.goodsEvaluateCountLabel.text = [NSString stringWithFormat:@"用户评价（%i）",_goodsModel.comments.totalPages];
            }else {
                goodsEvaluateCell.goodsEvaluateCountLabel.text = [NSString stringWithFormat:@"用户评价（0）"];
            }
            return goodsEvaluateCell;
        }else{
            EJSEvaluateTableViewCell *evaluateCell = [tableView dequeueReusableCellWithIdentifier:@"EJSEvaluateTableViewCell" forIndexPath:indexPath];
            [evaluateCell setEvaluateModel:_goodsModel.comments.list[indexPath.row - 1]];
            return evaluateCell;
        }
    }else if(indexPath.section == 2){
        EJSGoodsDetailTableViewCell *detailCell = [tableView dequeueReusableCellWithIdentifier:@"EJSGoodsDetailTableViewCell" forIndexPath:indexPath];
        [detailCell setContent:_goodsModel.content];
        return detailCell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 2){
        return 0.01;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [[UITableViewHeaderFooterView alloc] init];
    footerView.contentView.backgroundColor = UIColorFromRGB(0xf3f4f6);
    return footerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:indexPath];

    if (indexPath.section == 1 && indexPath.row == 0){
        EJSGoodsEvaluateListViewController *goodsEvaluateVC = [[EJSGoodsEvaluateListViewController alloc] initWithNibName:@"EJSGoodsEvaluateListViewController" bundle:nil];
        goodsEvaluateVC.spuId = self.goodsId;
        [self.navigationController pushViewController:goodsEvaluateVC animated:YES];
    }
}

@end

